package top.zerozoo.learn.grade.servlet;

import org.apache.commons.beanutils.BeanUtils;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.MajorService;
import top.zerozoo.learn.grade.service.StudentService;
import top.zerozoo.learn.grade.vo.StudentAddInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/studentAdd.do")
public class StudentAddServlet extends HttpServlet {
    private final StudentService studentService = ServiceFactory.get(StudentService.class);
    private final MajorService majorService = ServiceFactory.get(MajorService.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        if(parameterMap.size()==0){
            req.setAttribute("majors", majorService.findAll());
            req.getRequestDispatcher("/studentAdd.jsp").forward(req,resp);
            return;
        }
        StudentAddInfo studentAddInfo = new StudentAddInfo();
        try {
            BeanUtils.populate(studentAddInfo, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        studentService.insert(studentAddInfo.toStudent());
        resp.sendRedirect(req.getContextPath()+"/studentList.do");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
